﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Inovout.Web.Mvc
{
    public static class IdentityExtensions
    {
        public static int[] GetCompanyIds(this IIdentity identity)
        {
            ClaimsIdentity claimsIdentity = identity as ClaimsIdentity;
            Claim companyClaim = claimsIdentity.FindFirst(Constants.CompanyClaimType);
            var companyJson = (companyClaim != null) ? companyClaim.Value : "";
            JArray jarry = (JArray)JsonConvert.DeserializeObject(companyJson);
            List<int> listCompanyIds = new List<int>();
            int[] companyIds = { };
            if (jarry != null)
            {
                foreach (var obj in jarry)
                {
                    listCompanyIds.Add(Convert.ToInt16(((JObject)obj)["id"]));
                }
            }
            companyIds = listCompanyIds.ToArray();
            return companyIds;
        }

        public static void SetCompanyIds(this IIdentity identity, int[] companyIds)
        {
            ClaimsIdentity claimsIdentity = identity as ClaimsIdentity;

            //  //退出
            //    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);

            //  if (!string.IsNullOrEmpty(returnUrl))
            //  {
            //      return Redirect(returnUrl);
            //  }
            //  else
            //  {
            //      return Redirect("~/");
            //  }
            //  //重新登陆

            //  string provider = credential.GetType().Name.Substring(0, credential.GetType().Name.Length - "Credential".Length);
            //  ViewBag.ReturnUrl = returnUrl;
            //  if (!ModelState.IsValid)
            //  {
            //      return View(provider, credential);
            //  }

            //  IMembershipUser membershipUser = credentialValidator.Validate(credential);
            //  if (membershipUser == null)
            //  {
            //      ModelState.AddModelError("Code", "验证码错误");
            //      return View(provider, credential);
            //  }
            //  var authentication = HttpContext.GetOwinContext().Authentication;
            //  authentication.SignIn(
            //    new AuthenticationProperties { IsPersistent = isPersistent },
            //    new ClaimsIdentity(new[] { new Claim(ClaimsIdentity.DefaultNameClaimType, membershipUser.Identity.ToString()) }, provider)
            //);
            //  return View();
            //return new HttpUnauthorizedResult();
        }



    }

}
